package com.kingoe.shardingdj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingoe.shardingdj.entity.TbCommodityInfo;
import com.kingoe.shardingdj.mapper.TbCommodityInfoMapper;
import com.kingoe.shardingdj.service.TbCommodityInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 通过sharding jdbc实现读写分离
 * @author jinwu
 */
@Slf4j
@Service
public class TbCommodityInfoServiceImpl extends ServiceImpl<TbCommodityInfoMapper, TbCommodityInfo> implements TbCommodityInfoService {

    @Autowired
    private TbCommodityInfoMapper tbCommodityInfoMapper;

    @Override
    public List<TbCommodityInfo> getCommodityInfoList() {
        return tbCommodityInfoMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertCommodityInfo(String commodityName, String commodityPrice, String description, Integer number) {
        TbCommodityInfo tbCommodityInfo = new TbCommodityInfo();
        tbCommodityInfo.setCommodityName(commodityName);
        tbCommodityInfo.setCommodityPrice(commodityPrice);
        tbCommodityInfo.setNumber(number);
        tbCommodityInfo.setDescription(description);
        boolean result = tbCommodityInfoMapper.insert(tbCommodityInfo) == 1;
        /**
         * 同一线程且同一数据库连接内，如有写入操作，以后的读操作均从主库读取，用于保证数据一致性。
         */
        TbCommodityInfo info = tbCommodityInfoMapper.getLastInfo();
        log.info("info: {}", JSONObject.toJSONString(info));
        return result;
    }

}
